<template>
    <div>
        <el-card class="box-card">
            <!--1. 条件查询-->
            {{studentSearch}}
            <el-form :inline="true" :model="studentSearch" class="demo-form-inline">
                <el-form-item label="学生姓名">
                    <el-input v-model="studentSearch.sname" placeholder="学生姓名"></el-input>
                </el-form-item>
                <el-form-item label="学生住址">
                    <el-input v-model="studentSearch.addr" placeholder="学生住址"></el-input>
                </el-form-item>
                <el-form-item label="所在班级">
                    <el-select v-model="studentSearch.cid" placeholder="所在班级">

                        <el-option label="所有班级" value="0" ></el-option>
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                    </el-select>
                </el-form-item>
                    <el-button type="primary" @click="search"  icon="el-icon-search" >查询</el-button>
                    <el-button type="success" @click="add"  icon="el-icon-plus" >添加</el-button>

            </el-form>
            <!--2. 学生列表展示-->
            <el-table
                    :data="students"
                    style="width: 100%">
                <el-table-column
                        label="学号"
                        prop="sid"
                        align="center"
                        width="100">
                </el-table-column>
                <el-table-column
                        label="姓名"
                        align="center"
                        prop="sname"
                        width="180"/>
                <el-table-column
                        label="性别"
                        prop="sex"
                        align="center"
                        width="180"/>
                <el-table-column
                        label="年龄"
                        prop="age"
                        align="center"
                        width="180"/>
                <el-table-column
                        label="住址"
                        prop="addr"
                        align="center"
                        width="180"/>
                <el-table-column
                        label="所在班级"
                        prop="cname"
                        align="center"
                        width="180"/>
                <el-table-column label="操作" align="center" width="220px">
                    <template slot-scope="scope">
                        <el-button
                                icon="el-icon-edit"
                                size="mini"
                                plain
                                type="primary"
                                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                                size="mini"
                                icon="el-icon-delete"
                                plain
                                type="danger"
                                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--3. 分页插件-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"

                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <el-dialog :title="title" :visible.sync="dialogFormVisible"  :close-on-click-modal="false">
            {{student}}
            <el-form :model="student" :rules="rules" ref="studForm">
                <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                    <el-input v-model="student.sname" autocomplete="off" placeholder="请输入学生姓名"></el-input>
                </el-form-item>
                <el-form-item label="学生性别" :label-width="formLabelWidth"  prop="sex">
                    <!--<el-select v-model="student.sex" placeholder="请选择学生性别" style="width:100%">-->
                    <!--    <el-option label="男" value="男"></el-option>-->
                    <!--    <el-option label="女" value="女"></el-option>-->
                    <!--</el-select>-->
                    <el-radio v-model="student.sex" label="男">男</el-radio>
                    <el-radio v-model="student.sex" label="女">女</el-radio>
                </el-form-item>
                <el-form-item label="学生年龄" :label-width="formLabelWidth"  prop="age">
                    <el-input v-model.number="student.age" autocomplete="off" placeholder="请输入学生年龄"></el-input>
                </el-form-item>
                <el-form-item label="学生住址" :label-width="formLabelWidth"  prop="addr">
                    <el-input v-model="student.addr" autocomplete="off" placeholder="请输入学生住址"></el-input>
                </el-form-item>
                <el-form-item label="所在班级" :label-width="formLabelWidth"  prop="cid">
                    <el-select v-model="student.cid" placeholder="请选择所在班级"  style="width:100%">
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "student",
        data(){
            const ageValidator = (rule, value, callback) =>{      //自定义校验证规则
                if(!value){
                    callback(new Error('请输入年龄.'));
                }else if(isNaN(value)){
                    callback(new Error("年龄必须是数字."))
                }
                callback();
            };
            return {
                students: [],
                studentSearch:{},
                classes:[],
                page:1,
                pageSize:5,
                total:100,
                dialogFormVisible:false,
                formLabelWidth:'120px',
                title:'添加学生',
                student:{},
                rules: {
                    sname: [
                        {required: true, message: '请输入学生姓名', trigger: 'blur'},
                    ],
                    sex: [
                        { required: true, message: '请选择性别', trigger: 'change' }
                    ],
                    age: [
                        {
                            validator: ageValidator,
                            trigger: 'blur'
                        },
                    ],
                    addr: [
                        {required: true, message: '请输入学生住址', trigger: 'blur'},
                    ],
                    cid: [
                        { required: true, message: '请选择所在班级', trigger: 'change' }
                    ],
                }
            }
        },
        created() {
          //1. 查询所有学生
          //this.findAllStudents();
          //2. 查询所有班级
          this.findAllClasses();
          //3. 调用search
          this.search();
        },
        methods: {
            //1. 查询所有学生
            findAllStudents(){
                this.axios.get("/student?cmd=list").then(resp=>{
                    console.log(resp.data);
                    this.students = resp.data;
                })
            },
            //2. 查询所有班级
            findAllClasses(){
                this.axios.get("/classes?cmd=list").then(resp=>{
                    console.log(resp.data);
                    this.classes = resp.data;
                })
            },
            //3. 条件带分页查询
            //分析：需要向后台传入：page,pageSize,查询条件参数对象
            search(){
                console.log("page=",this.page,"pagesize=",this.pageSize);
                this.axios.post(`/student?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,"stud="+JSON.stringify(this.studentSearch))
                .then((resp)=>{
                    console.log(resp.data);
                    //3.1 动态显示表格数据
                    this.students = resp.data.list;
                    //3.2 更新总记录数，由系统帮我们计算总页数
                    this.total = resp.data.total;
                })
            },
            //4. 添加学生对话框
            add(){
                //4.1 修改对话框标题文字
                this.title = "添加学生"
                //4.2 显示对话框
                this.dialogFormVisible = true;
                //4.3 恢复学生对象
                this.student = {};
            },
            //5. 编辑学生
            handleEdit(index, row) {
                console.log(index, row);
                this.student = row;
                //5.1 修改标题
                this.title = "修改学生";
                //5.2 显示对话框
                this.dialogFormVisible = true;
            },
            //6. 删除学生
            handleDelete(index, row) {
                let _this = this;
                this.$confirm(`你真的要删除学生[${row.sname}]?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {     //点击了确定按钮后，向后台发送请求
                    this.axios.get(`/student?cmd=delete&sid=${row.sid}`).then(resp=>{
                        if(resp.data.code === 0){
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                                onClose(){
                                    // 刷新页面
                                    _this.search();
                                }
                            });
                        }
                    })
                })
            },
            // 页大小(pageSize)改变时触发
            handleSizeChange(pageSize) {
                this.pageSize = pageSize;
                console.log(`每页 ${pageSize} 条`);
            },
            // 当前页(page)改变时触发
            handleCurrentChange(page) {
                this.page = page;
                console.log(`当前页: ${page}`);
                this.search();

            },
            //保存学生
            save(){
                let _this = this;
                this.$refs['studForm'].validate(valid=>{
                    console.log("valid:",valid);
                    if(valid){      //valid：如果为true,代表所有控件校验通过，只要有一个不通过就是false
                        //1. 定义提交的url地址
                        let url = "/student?cmd=add";
                        //2. 判断如果this.student.sid有值，就是修改操作
                        if(this.student.sid){
                            url = "/student?cmd=update";
                        }
                        //3. 开始异步提交数据
                        this.axios.post(url,"stud="+JSON.stringify(this.student)).then(resp=>{
                                if(resp.data.code == 0){        //操作成功
                                    this.$message({
                                        message: `恭喜你，${this.student.sid ? '修改成功!':'添加成功!'}`,
                                        type: 'success',
                                        onClose(){          //当消息框关闭时，执行的操作!
                                            //3.1 刷新页面
                                            _this.search();
                                            //3.2 关闭对话框
                                            _this.dialogFormVisible = false;
                                        }
                                    });

                                }
                                else{
                                    this.$message({
                                        message: resp.data.msg,
                                        type: 'warning'
                                    });
                                }
                        })
                    }
                })
            }
        }
    }
</script>

<style scoped>
    .el-pagination{
        text-align: right;
        margin-top: 20px;
    }
</style>